<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>异步编程</title>
</head>

<body>
    <script>
        //执行async函数，返回的都是Promise对象
        async function test1() {
            return 1;//相当于return Promise.resolve(1)
        }

        async function test2() {
            return Promise.resolve(2);
        }
        const result1 = test1();
        const result2 = test2();
        console.log(result1);//Promise对象
        console.log(result2);//Promise对象

        //Promise.then成功的情况对应await
        async function test3() {
            const p3 = Promise.resolve(3);
            //.then 的方式
            p3.then(data => {
                console.log('data3', data)//3
            })

            //await的方式
            const data3 = await p3;
            console.log('data3', data3)//3
            //.then和await打印的值相同，可以说明Promise.then成功的情况对应await
        }
        test3()

        async function test4() {
            const data4 = await 4;//相当于await Promise.resolve(4)
            console.log('data4', data4)
        }
        test4()

        async function test5() {
            const data5 = await test1();//相当于await Promise.resolve(1)
            console.log('data5', data5)
        }
        test5()

        //Promise.catch 异常的情况对应try...catch
        //异常不能被捕获的情况
        async function test6() {
            const p6 = Promise.reject(6);
            const data6 = await p6;
            console.log(data6);//Uncaught (in promise) 6 —— 异常不能被捕获
        }
        test6()

        async function test7() {
            const p7 = Promise.reject(7);
            try {
                const data7 = await p7;
                console.log(data7);
            } catch (err) {
                console.error(err);//7 —— 异常可以被捕获
            }
        }
        test7()
    </script>
</body>

</html>